package com.zretc.answer.controller;

import com.zretc.answer.service.AnswerService;
import com.zretc.api.pojo.Answer;
import com.zretc.common.constant.SecurityConstant;
import com.zretc.common.entity.R;
import com.zretc.common.entity.RespResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/ir")
public class AnswerController {
    @Autowired
    private AnswerService answerService;
    @GetMapping("/showAnswersOfQuestionByAmount")
    public RespResult showAnswersOfQuestionByAmount(@RequestParam("index")Integer index,
                                                    @RequestParam("pageNum")Integer pageNum,
                                                    @RequestParam("questionId")Integer qId)
    {
        List<Answer> result=answerService.queryAnswersByAmountByQuestionId(index, pageNum, qId);
        if(CollectionUtils.isEmpty(result))return R.fail(500,"服务器错误");
        return R.success(result);
    }
    @PostMapping("/userAnswer")
    public RespResult userAnswer(@RequestBody Answer answer,HttpServletRequest req)
    {
            Integer fromId= Integer.valueOf(req.getHeader(SecurityConstant.AUTHENTICATION_KEY));
            answer.setFromId(fromId);
            if(!answerService.giveAnswer(answer))return R.fail(500,"服务器错误");
            return R.success(null);
    }
    @PostMapping("/userDeleteAnswer")
    public RespResult userDeleteAnswer(@RequestBody Map<String,Object> map, HttpServletRequest req)
    {
        Integer id=(Integer) map.get("id");
        Integer fromId= Integer.valueOf(req.getHeader(SecurityConstant.AUTHENTICATION_KEY));
        if(!answerService.deleteAnswerByUser(id,fromId))return R.fail(500,"服务器错误");
        return R.success(null);
    }
    @PostMapping("/publisherDeleteAnswer")
    public RespResult publisherDeleteAnswer(@RequestBody Map<String,Object> map, HttpServletRequest req)
    {
        Integer id=(Integer) map.get("id");
        Integer iRPublisherId= Integer.valueOf(req.getHeader(SecurityConstant.AUTHENTICATION_KEY));
        if (!answerService.deleteAnswerByIRPublisher(id,iRPublisherId))return R.fail(500,"服务器错误");
        return R.success(null);
    }
}
